package com.feilong.cn.mybatis.autoV2.handler;



import com.feilong.cn.mybatis.autoV2.config.AutoConfiguration;
import com.feilong.cn.mybatis.autoV2.statement.MappedStatement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by yangxulong on 2018/4/2.
 */
public class AutoSimpleStatementHandler {
    private AutoConfiguration configuration;
    private AutoResultSetHandler autoResultSetHandler;

    public AutoSimpleStatementHandler(AutoConfiguration configuration, AutoResultSetHandler autoResultSetHandler) {
        this.configuration = configuration;
        this.autoResultSetHandler = autoResultSetHandler;
    }

    public AutoSimpleStatementHandler(AutoConfiguration configuration) {
        this(configuration, new AutoResultSetHandler(configuration));
    }

    public <E> E query(String strStatement, Object parameter) {
        try {
            //JDBC
            Connection conn = getConnection();
            MappedStatement mappedStatement = configuration.getMappedStatement(strStatement);
            //TODO ParameterHandler

            String strSql = mappedStatement.getSql();
            PreparedStatement pstmt = conn.prepareStatement(strSql);

            if(parameter.getClass().getName().equals("java.lang.String")){
                pstmt.setString(1,parameter.toString());
            }
            if(parameter.getClass().getName().equals("java.lang.Integer")){
                pstmt.setInt(1,Integer.valueOf(parameter.toString()));
            }
            pstmt.execute();

            //ResultSetHandler
            return (E) autoResultSetHandler.handle(pstmt.getResultSet(), mappedStatement.getReturnType());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public Connection getConnection() throws SQLException {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://10.168.100.164:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
